﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SiyinPractice.Interface.AccessControl;
using SiyinPractice.Interface.Maintenance;
using SiyinPractice.Interface.ProjectManagement.ProjectManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SiyinPractice.Application.ProjectManagement.ProjectManage.Help
{
    /// <summary>
    /// 企业微信服务类
    /// </summary>
    public class WeChatMsgReminderService : BackgroundService
    {
        private readonly IConfiguration _config;

        private readonly ILogger<WeChatMsgReminderService> _logger;

        // private readonly IAccountPasswordService _projectSettlementEfRepository;
        private readonly IServiceProvider _serviceProvider;

        private TimeCycleHelper _timeCycleHelper { get; set; }

        //private string weComCId;//企业Id①
        //private string weComSecret ; //应用secret②
        //private string weComAId ; //应用ID③
        //private string weComTouId ;
        //private int WXDefaultTimerInterval;

        //private int WXOldDefaultTimerInterval;
        //private int DDDefaultTimerInterval;

        //private int DDOldDefaultTimerInterval;
        private int DefaultTimerInterval;

        private int OldDefaultTimerInterval;

        private int defaultTimer = 7200;
        //   private Test _test;

        public WeChatMsgReminderService(IConfiguration config, TimeCycleHelper timeCycleHelp, ILogger<WeChatMsgReminderService> logger, IServiceProvider serviceProvider

            )
        {
            this._config = config;
            this._logger = logger;
            this._timeCycleHelper = timeCycleHelp;
            this._serviceProvider = serviceProvider;

            //using (var scope = serviceProvider.CreateScope())
            //{
            //    var _weChatService = scope.ServiceProvider.GetRequiredService<IWeChatService>();
            //    _weChatDto = await _weChatService.GetParentSetting();
            //}

            // _projectSettlementEfRepository = projectSettlementEfRepository;
        }

        public async void ServiceDo()
        {
            //...需要执行的任务代码

            using var scope = _serviceProvider.CreateScope();
            var _projectSettlement = scope.ServiceProvider.GetRequiredService<IAccountPasswordService>();
            var _weChatService = scope.ServiceProvider.GetRequiredService<IWeChatService>();
            var _userAppService = scope.ServiceProvider.GetRequiredService<IUserAppService>();
            var list = await _projectSettlement.GetAccountPasswordDto("企业微信");
            var template = await _weChatService.GetAllAsync();
            var userDtos = _userAppService.GetAllAsync();
            var parentTemplate = await _weChatService.GetParentSetting();
            if (template != null && parentTemplate != null)
            {
                DefaultTimerInterval = (int)(parentTemplate?.DefaultTimerInterval > 0 ? parentTemplate?.DefaultTimerInterval * 1000 : 3600 * 1000);
                if (OldDefaultTimerInterval != DefaultTimerInterval)
                {
                    OldDefaultTimerInterval = DefaultTimerInterval;
                    this._timeCycleHelper.Stop();
                    this._timeCycleHelper.Start(DefaultTimerInterval, new TimeCycle(new Guid(), this.ServiceDo));
                    this._logger.LogInformation("修改定时器时间");
                }
                else
                {
                    foreach (var item in list)
                    {
                        var now = DateTime.Now;
                        if (now > item.ReminderTime)
                        {
                            TimeSpan ts = now - Convert.ToDateTime(item.ReminderTime);  //计算时间差

                            var seconds = ts.TotalSeconds;  //将时间差转换为秒
                                                            // var hour = (Convert.ToDateTime(item.EndTime) - Convert.ToDateTime(item.ReminderTime)).TotalHours;   //将时间差转换为秒
                            var hour = Convert.ToDouble((Convert.ToDateTime(item.EndTime) - Convert.ToDateTime(item.ReminderTime)).TotalHours).ToString("0.00");
                            //var deefaultTimer = (DefaultTimerInterval / 1000);

                            if (!string.IsNullOrEmpty(item.ReminderTemplate))
                            {
                                var msgreminder = template.FirstOrDefault(x => Convert.ToString(x.Id) == item.ReminderTemplate);
                                if (msgreminder != null)
                                {
                                    defaultTimer = (int)(parentTemplate?.DefaultTimer > 0 ? parentTemplate?.DefaultTimer : 7200);
                                    if ((seconds) < defaultTimer)
                                    {
                                        TextModel textModel2 = new TextModel();
                                        var AccountName = item.AccountName;
                                        var ReminderTime = item.ReminderTime.ToString();
                                        var WebsiteUrl = item.WebsiteUrl;
                                        //此处文本 支持超链接

                                        var templatetext = msgreminder.Content;
                                        templatetext = templatetext.Replace("{" + "AccountName}", AccountName);
                                        templatetext = templatetext.Replace("{" + "Hour}", hour);
                                        templatetext = templatetext.Replace("{" + "ReminderTime}", ReminderTime);
                                        templatetext = templatetext.Replace("{" + "WebsiteUrl}", WebsiteUrl);
                                        textModel2.content = templatetext;
                                        switch (item.MsgReminderType)
                                        {
                                            case "企业微信":
                                                TextMsgModel textMsgModel = new TextMsgModel();
                                                textMsgModel.msgtype = msgreminder.Msgtype;
                                                textMsgModel.agentid = parentTemplate.Agentid;
                                                textMsgModel.touser = msgreminder.Touser;
                                                string toparty = "";
                                                string Topartys = msgreminder.Toparty;
                                                foreach (var user in userDtos)
                                                {
                                                    if (Topartys.Split("|").FirstOrDefault(x => x == Convert.ToString(user.DeptId)) != null && !string.IsNullOrEmpty(user.WeChat))
                                                    {
                                                        toparty = toparty + user.WeChat + "|";
                                                    }
                                                }
                                                if (toparty != "")
                                                {
                                                    toparty += textMsgModel.touser;
                                                }

                                                var zzztextMsgModel = string.Join("|", toparty.Split("|").Distinct());
                                                //textMsgModel.toparty = msgreminder.Toparty;
                                                //textMsgModel.totag = msgreminder.Totag;
                                                textMsgModel.duplicate_check_interval = msgreminder.Duplicate_check_interval > 0 ? msgreminder.Duplicate_check_interval : 1800;
                                                textMsgModel.enable_duplicate_check = msgreminder.Enable_duplicate_check;
                                                textMsgModel.enable_id_trans = msgreminder.Enable_id_trans;
                                                textMsgModel.safe = msgreminder.Safe;

                                                textMsgModel.text = textModel2;
                                                SendToWeCom(parentTemplate.CorpId, parentTemplate.CorpSecret, textMsgModel);
                                                await _projectSettlement.UpdateAccountPassword(item.Id.Value);
                                                break;

                                            //case "WeChatGroup":
                                            //    TextWeChatGroup textWeChatGroup = new TextWeChatGroup();
                                            //    textWeChatGroup.msgtype = msgreminder.FirstOrDefault(x => x.DictName == "msgtype")?.DictVaule.ToString();
                                            //    textWeChatGroup.chatid = msgreminder.FirstOrDefault(x => x.DictName == "chatid")?.DictVaule.ToString();
                                            //    textWeChatGroup.safe = msgreminder.FirstOrDefault(x => x.DictName == "safe")?.DictVaule.ToString();

                                            //    textWeChatGroup.text = textModel2;
                                            //    SendToWeChatGroup(msgreminder.FirstOrDefault(x => x.DictName == "corpid")?.DictVaule.ToString(), msgreminder.FirstOrDefault(x => x.DictName == "corpsecret")?.DictVaule.ToString(), textWeChatGroup);
                                            //    await _projectSettlement.UpdateAccountPassword(item.Id.Value);
                                            //    break;

                                            default:
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            this._logger.LogInformation($"定时任务：企业微信服务已启动...");
            // this.Init(scope);
            DefaultTimerInterval = 60 * 1000; //789
            OldDefaultTimerInterval = DefaultTimerInterval;
            //List<TimeCycle> timeCycles = new List<TimeCycle>
            //{
            //    new TimeCycle(new Guid(), this.ServiceDo),
            //    new TimeCycle(new Guid(), this.ServiceDingDing)
            //};
            this._timeCycleHelper.Start(DefaultTimerInterval, new TimeCycle(new Guid(), this.ServiceDo));
            return Task.CompletedTask;
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            this._logger.LogInformation($"同步服务已停止...");
            this._timeCycleHelper.Stop();
            return Task.CompletedTask;
        }

        public string SendToWeCom(string corpid, string corpsecret, TextMsgModel textMsgModel)
        {
            //var weComCId = "wwcb45444679e5bf81";//企业Id①
            //var weComSecret = "iGxQ1_tWcB_c_iwyQ-uzIc3_bU70dDlwS3A6o5OK8G4"; //应用secret②
            //var weComAId = "1000002"; //应用ID③
            //var weComTouId = "@all";//发送给谁  如果是所有人的话 这里就是@all
            //                        // 获取Token   后缀中 debug=1 接口可以返回具体的信息 这个官方文档上也有介绍
            string getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret + "&debug=1";
            string str = HttpClientHelper.GetResponse(getTokenUrl);
            Dictionary<string, string> jobject = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
            if (jobject["errcode"].ToString() == "0" && jobject["errmsg"].ToString() == "ok")
            {
                string token = jobject["access_token"].ToString();
                //获取用户 此处列举了一下 通过用户在企业微信中的手机号 获取企业微信标识的方式 用处你懂的
                //string dd = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + token;
                //Dictionary<string, string> mobileDic = new Dictionary<string, string>();
                //mobileDic.Add("mobile", "xxx");
                //string result1 = HttpClientHelper.PostResponse(dd, JsonConvert.SerializeObject(mobileDic));

                //发送文本消息
                string postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token + "&debug=1";
                //TextMsgModel textMsgModel = new TextMsgModel();
                ////用户在企业微信中的账号标识，可以通过手机号获取，也可以直接在企业微信具体查看，查看方式参照我的CSDN博客
                //textMsgModel.touser = weComTouId;
                ////发送的消息类型 此处为文本形式
                //textMsgModel.msgtype = "text";
                //textMsgModel.agentid = weComAId;
                //TextModel textModel2 = new TextModel();
                ////此处文本 支持超链接
                //textModel2.content = text;
                //textMsgModel.text = textModel2;
                string result = HttpClientHelper.PostResponse(postUrl, JsonConvert.SerializeObject(textMsgModel));
                this._logger.LogInformation(JsonConvert.SerializeObject(textMsgModel));
                this._logger.LogInformation(result);
            }
            return "-1";
        }

        public string SendToWeChatGroup(string corpid, string corpsecret, TextWeChatGroup textMsgModel)
        {
            //var weComCId = "wwcb45444679e5bf81";//企业Id①
            //var weComSecret = "iGxQ1_tWcB_c_iwyQ-uzIc3_bU70dDlwS3A6o5OK8G4"; //应用secret②
            //var weComAId = "1000002"; //应用ID③
            //var weComTouId = "@all";//发送给谁  如果是所有人的话 这里就是@all
            //                        // 获取Token   后缀中 debug=1 接口可以返回具体的信息 这个官方文档上也有介绍
            string getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret + "&debug=1";
            string str = HttpClientHelper.GetResponse(getTokenUrl);
            Dictionary<string, string> jobject = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
            if (jobject["errcode"].ToString() == "0" && jobject["errmsg"].ToString() == "ok")
            {
                string token = jobject["access_token"].ToString();
                //获取用户 此处列举了一下 通过用户在企业微信中的手机号 获取企业微信标识的方式 用处你懂的
                //string dd = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + token;
                //Dictionary<string, string> mobileDic = new Dictionary<string, string>();
                //mobileDic.Add("mobile", "xxx");
                //string result1 = HttpClientHelper.PostResponse(dd, JsonConvert.SerializeObject(mobileDic));

                //发送群文本消息
                string postUrl = " https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=" + token + "&debug=1";

                string result = HttpClientHelper.PostResponse(postUrl, JsonConvert.SerializeObject(textMsgModel));
                this._logger.LogInformation(result);
            }
            return "-1";
        }

        //public string SendToDingDing(string appkey, string appsecret, DingDingMsgModel dingDingMsgModel)
        //{
        //    string getTokenUrl = "https://oapi.dingtalk.com/gettoken?appkey=" + appkey + "&appsecret=" + appsecret;
        //    string str = HttpClientHelper.GetResponse(getTokenUrl);
        //    Dictionary<string, string> jobject = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
        //    if (jobject["errcode"].ToString() == "0" && jobject["errmsg"].ToString() == "ok")
        //    {
        //        string token = jobject["access_token"].ToString();

        //        string postUrl = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + token;
        //        var ss = JsonConvert.SerializeObject(dingDingMsgModel);
        //        string result = HttpClientHelper.PostResponse(postUrl, ss);
        //        this._logger.LogInformation(result);
        //    }
        //    return "-1";
        //}
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    //string joke = _jokeService.GetJoke();
                    _logger.LogWarning("{Joke}", "111");

                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "{Message}", ex.Message);

                // Terminates this process and returns an exit code to the operating system.
                // This is required to avoid the 'BackgroundServiceExceptionBehavior', which
                // performs one of two scenarios:
                // 1. When set to "Ignore": will do nothing at all, errors cause zombie services.
                // 2. When set to "StopHost": will cleanly stop the host, and log errors.
                //
                // In order for the Windows Service Management system to leverage configured
                // recovery options, we need to terminate the process with a non-zero exit code.
                Environment.Exit(1);
            }
        }
    }
}